﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace StudyEnglish.Application.Filter
{
    /// <summary>
    /// Category of filters
    /// </summary>
    public class FilterCategory<T> : BaseFilterCategory
    {
       
        public FilterCategory()
        {
            
        }

        public FilterCategory(string name) :base(name)
        {
            
        }
        /// <summary>
        /// List of filters (items) that belong to the category
        /// </summary>
        private readonly IList<FilterItem<T>> _items = new List<FilterItem<T>>();

        public override IList<BaseFilterItem> Items
        {
            get 
            {
                return (_items.Select(x => (BaseFilterItem) x).ToList());
            }
        }

        /// <summary>
        /// Adds items (filter) to the category
        /// </summary>
        /// <param name="item"></param>
        public void AddItem(FilterItem<T> item)
        {
            item.Key = SmartFilter<T>.NumberShift + _items.Count;
            item.ParentCategory = this;
            _items.Add(item);
        }


        /// <summary>
        /// returns list of selected item
        /// </summary>
        private IList<FilterItem<T>> SelectedPredicateItems
        {
            get { return (from x in _items where x.IsSelected == true select x).ToList(); }
        }

        public Expression<Func<T, bool>> GetFilterWhereCondition()
        {
            Expression<Func<T, bool>> result;
            if (SelectedPredicateItems.Count > 0)
            {
                result = PredicateBuilder.False<T>();
                foreach (var selectedItem in SelectedPredicateItems)
                {
                    result = result.Or(selectedItem.ItemPredicate);
                }
            }
            else
            {
                result = PredicateBuilder.True<T>();
            }
            return result;
        }
    }
}